package com.g4.shoppingsingle.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.SecureRandom;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;

@RestController
public class PayController {
    private final String APP_ID = "2021000118612406";       //APPID
    //应用私钥
    private final String APP_PRIVATE_KEY = "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCVGCSymvACg4EAhJQRfQjofpNGdE891TS8xWDGcwVAl3066gTb4BcUwcpCDPKihU0JO52ILlwGnVB61Koa1e1LS3hjYG6JxjzVvkpkfXfiJQvyOXyciZW7bqluXnRA6ifMx+bmQMqYIzxFzzTVmaC3PbInPE3glKFjeyZ4HXmfjZ727xTfTSwpyHfV6Ju5AUxdDtp+56vrLbejpYWEZ6bg9vQJPpVOq2wsuYFQL+V33xa9FVVKSej0xCEM9qWowjKE5aEi+6+JmkOSznJquIx2eyrHB2mYZ7ZvaM1OxlJq8KTdB593jhFE/y2rugC17vOFVyQ6cYJ3KGILSa/CSWwNAgMBAAECggEAOwkKTuZmrrgfdnMIpjwaMOUdr8ISNmubrDuDbFDS/ZZ+cbuEHQQIX6G0Up8J3CxoKoW+hNPGgJ/95AUdLe8TPMMvcjoWytsB76ifkFbWB2ef6VO18c3QyhyxXhBse9+7zqxA019IWSFqlkHLq+Be8O+vATYxqAFyPg/fVaRmKjSwwNiqdn2RrBd+1PsyCWublU6tb8PI8+zS7JFoGd9gW45BbhToURF23ZU1xO7dA6+feC+qgyE4F4c+QrtjaBxWhwRGqpmRh4v5J6vd6ZoMQSbSAaRKCHk1gIX4Jctgz7pOdJo/PdrSzUN9B4amuU1RUIwDGJe8/u/rQP8FoeiLiQKBgQDH9rJ4B2wwYOti7z0RadCVJbSOMVcAXU2IcpAGyqIbWu0gBtMlUVpLuWpOIKaOS93oOCn+D4cEXobGnJyzRgTMZ3+5vNy0Fanb6LhpcU/98IaBCF85gT+1hbMptRYz5czrolmwI0bPfqul8zU24RYez+HR3e4u1znbRtNEdewpOwKBgQC+4BoXb4Z1pFni1ziU8BgQDXFvLoRzNRyM76e6okIjp4O7TckxEerdkwPgUTW0WjnvKtHcsmNyFbkusniMDMIHeaYW66IgwHU42RfatklYSu6TIRunCV9OxWk8pnVHExZxeyalZiIycYXW42VL5MnjljZTmTHsd+PZuV8XfqerVwKBgAv/RR3mdBtC9VxuNh/BVX5dUMPnOe0PrAMvvGxr4+X4QpnVTv3CL8SzTyl41AVdj+bK19oiXFtqwHNSGiS3YrpQy1z9c9BqLFLBV68b2UzHDYrYUb5FfukJKIKsFrTuaKkKiI8Ezs7MLsg6G0s7nfQjTM0mn4+34gTB7xMAcDbZAoGAQedWmuji4BOTBYOSAbq0VDaQB/dju/OGnBLTMtl7RJw+G5nL8aliEocEO5tOk6rjffSm6TCerXFaswjkHlb5V2NlOVy6adyJnMs4NUfjIx0cKqivx4iw4529rDc9HwE0KpJ+0XTmMcyIjZ2OCBpCqtXehBbM6fyrKy2Z657LfZkCgYBibqAq/wuFdmHzMBaadmSbqKXnndGyTw+67vbwHhas9p6v+q1AYpO3dE7udhxw07ylQrggZxl9sR9dSZJId0UZiy0f3dbdAkRnU5XkrIp2avZqgAjC8ZfjcrRjUBO+Ikj2L1u8IpGkJGYowFTHEF5Orp6y6jdM3zynE/l30tuCmA==";
    private final String CHARSET = "UTF-8";
    //支付宝的公钥
    private final String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAguA7uN8bJ3G/yAe4f5toWJNAXy971jTLczp+Kf49+a1sAQyfXpm27OhnCsW+lnM9+FfiFwTaVH6x68N0KJLVy+KbnMYnDPmBMIuUm5XSxl1GjRJvuhKhJpzuswnI9c51bgayKVcvhY3OiQmKoTKnVdPbPiIxT++AaM5ULK3K5+8ymh0MujIwpy2P60C7LAMTV60C4fR/C8q+CzvEH/9m30fghoRO8XZ3FMIt2C/k8ykZuW66sikhiqA89R2a4DqZpz69lUZ8Gxv7QjHpIHfpx5aell9QkRej8qFU2etiDIALdm91G2pGWRumrxS3R0hPm3lWrgvlTaBtfpnGNjSMZQIDAQAB";
    //这是沙箱接口路径,正式路径为https://openapi.alipay.com/gateway.do
    private final String GATEWAY_URL ="https://openapi.alipaydev.com/gateway.do";
    private final String FORMAT = "JSON";
    //签名方式
    private final String SIGN_TYPE = "RSA2";
    //支付宝异步通知路径,付款完毕后会异步调用本项目的方法,必须为公网地址
    private final String NOTIFY_URL = "http://公网地址/notifyUrl";
    //支付宝同步通知路径,也就是当付款完毕后跳转本项目的页面,可以不是公网地址
    private final String RETURN_URL = "http://127.0.0.1:8080/returnUrl";


    @RequestMapping("/alipay")
    public void alipay(HttpServletResponse httpResponse) throws IOException {
        SecureRandom r=new SecureRandom();
        //实例化客户端,填入所需参数
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        //在公共参数中设置回跳和通知地址
        request.setReturnUrl(RETURN_URL);
        request.setNotifyUrl(NOTIFY_URL);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        //生成随机Id
        String out_trade_no = UUID.randomUUID().toString();
        //付款金额，必填
        String total_amount =Integer.toString(r.nextInt(9999999)+1000000);
        //订单名称，必填
        String subject ="奥迪A8 2016款 A8L 60 TFSl quattro豪华型";
        //商品描述，可空
        String body = "尊敬的会员欢迎购买奥迪A8 2016款 A8L 60 TFSl quattro豪华型";
        request.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + CHARSET);
        httpResponse.getWriter().write(form);// 直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }

    /**
     *
     * @param request
     * @param response
     * @return
     * @throws IOException
     * @throws AlipayApiException
     */
    @RequestMapping(value = "/returnUrl", method = RequestMethod.GET)
    public String returnUrl(HttpServletRequest request, HttpServletResponse response)
            throws IOException, AlipayApiException {
        System.out.println("=================================同步回调=====================================");

        // 获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("utf-8"), "utf-8");
            params.put(name, valueStr);
        }

        System.out.println(params);//查看参数都有哪些
        boolean signVerified = AlipaySignature.rsaCheckV1(params, ALIPAY_PUBLIC_KEY, CHARSET, SIGN_TYPE); // 调用SDK验证签名
        //验证签名通过
        if(signVerified){
            // 商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");

            // 支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");

            // 付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");

            System.out.println("商户订单号="+out_trade_no);
            System.out.println("支付宝交易号="+trade_no);
            System.out.println("付款金额="+total_amount);

            //支付成功，修复支付状态
            //payService.updateById(Integer.valueOf(out_trade_no));
            return "ok";//跳转付款成功页面
        }else{
            return "no";//跳转付款失败页面
        }
    }
}
